package com.loren.tetris.windows;

import com.loren.tetris.data.GameData;
import com.loren.tetris.data.constant.DataConstant;
import com.loren.tetris.service.GameService;
import com.loren.tetris.utils.AssistiveUtils;
import com.loren.tetris.windows.ui.Box;
import com.loren.tetris.windows.ui.*;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class GamePanel extends JPanel {

    private static final long serialVersionUID = 7998242129354865367L;

    private GameData gameData;

    private JButton btnGameStart;

    private List<Box> gameBoxList;

    public GamePanel() {
        this.setLayout(null);
        this.setPreferredSize(new Dimension(DataConstant.GAME_PANEL_WIDTH, DataConstant.GAME_PANEL_HEIGHT));
        this.setBackground(DataConstant.COLOR_BLACK);
        this.initGameButton();
        this.setFocusable(true);
        this.initGameData();
    }

    /**
     * 初始化游戏数据
     */
    private void initGameData() {
        this.gameData = new GameData();
        this.loadGameBoxList();
    }

    /**
     * 加载游戏边框
     */
    private void loadGameBoxList() {
        this.gameBoxList = new ArrayList<>();
        this.gameBoxList.add(new BoxExplain(20, 20, 300, 290, this.gameData));
        this.gameBoxList.add(new BoxRecord(20, 330, 300, 290, this.gameData));
        this.gameBoxList.add(new BoxBlock(340, 20, 300, 600, this.gameData));
        this.gameBoxList.add(new BoxButton(660, 20, 300, 135, this.gameData));
        this.gameBoxList.add(new BoxNext(660, 175, 140, 135, this.gameData));
        this.gameBoxList.add(new BoxGrade(820, 175, 140, 135, this.gameData));
        this.gameBoxList.add(new BoxCount(660, 330, 300, 150, this.gameData));
        this.gameBoxList.add(new BoxPerson(660, 500, 300, 120, this.gameData));
    }

    /**
     * 初始化游戏按钮
     */
    private void initGameButton() {
        this.btnGameStart = new JButton("开始游戏");
        this.btnGameStart.setFont(new Font(AssistiveUtils.getFontFamily(), Font.BOLD, 28));
        this.btnGameStart.setBackground(Color.white);
        this.btnGameStart.setForeground(DataConstant.COLOR_BOX_BORDER);
        this.btnGameStart.setFocusPainted(false);
        this.btnGameStart.setBorderPainted(false);
        this.btnGameStart.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        this.btnGameStart.setLocation(730, 65);
        this.btnGameStart.setSize(160, 45);
        this.add(this.btnGameStart);
        this.btnGameStart.addActionListener(e -> {
            this.initGameData();
            this.gameData.setGameOver(false);
            this.btnGameStart.setEnabled(false);
            this.addKeyListener(new GameService(this, this.gameData));
            this.repaint();
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.gameBoxList.forEach(box -> box.paint(g));
    }

    public JButton getBtnGameStart() {
        return btnGameStart;
    }
}
